<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/11/19
 * Time: 15:45
 */

namespace app\common\model;


use think\Db;
use think\Exception;

class CategoryAndBrand extends BaseModel
{

    protected $deleteTime = false;

    /**
     * 关联获取品牌排信息
     * @return \think\model\relation\BelongsTo
     */
    public function brand() {
        return $this->belongsTo('Brand');
    }

    /**
     * 关联获取分类信息
     * @return \think\model\relation\BelongsTo
     */
    public function category() {
        return $this->belongsTo('Category');
    }

    /**
     * 分类关联品牌
     * @param $category_id
     * @param $brand_ids
     * @return \think\response\Json
     * @throws \Exception
     */
    public static function categoryRelevanceBrand($category_id, $brand_ids) {
        Db::startTrans();
        try {
            // 删除分类之前关联的品牌数据
            self::where('category_id', '=', $category_id)->delete(true);

            // 重新添加关联
            if ($brand_ids) {
                $data = [];
                foreach ($brand_ids as $id) {
                    $data[] = [
                        'category_id' => $category_id,
                        'brand_id' => $id
                    ];
                }
                (new self())->saveAll($data);
            }
            Db::commit();
            return return_data('保存成功！');
        } catch (Exception $e) {
            Db::rollback();
            return return_data($e->getMessage(), 1);
        }
    }

    /**
     * 品牌关联分类
     * @param $brand_id
     * @param $category_ids
     * @return \think\response\Json
     * @throws \Exception
     */
    public static function brandRelevanceCategory($brand_id, $category_ids) {
        Db::startTrans();
        try {
            // 删除分类之前关联的品牌数据
            self::where('brand_id', '=', $brand_id)->delete(true);

            // 重新添加关联
            if ($category_ids) {
                $data = [];
                foreach ($category_ids as $id) {
                    $data[] = [
                        'brand_id' => $brand_id,
                        'category_id' => $id
                    ];
                }
                (new self())->saveAll($data);
            }

            Db::commit();
            return return_data('保存成功！');
        } catch (Exception $e) {
            Db::rollback();
            return return_data($e->getMessage(), 1);
        }
    }

    /**
     * 获取分类或者品牌的id集合
     * @param $where
     * @param $field
     * @return array
     */
    public static function getIds($where, $field){
        return self::where($where)->column($field);
    }
}